package controller;

import java.util.ArrayList;
import java.util.Date;

import dao.BoardMementoDAO;
import dao.PoemDAO;
import entity.Board;
import entity.BoardMemento;
import entity.Poem;
import gui.BoardApplication;

/**
 * This is the controller for Publishing poem to the wall.
 */
public class PublishController {
	private Board board;
	private BoardApplication gui;
	
	/**
	 * Constructor of PublishController.
	 */
	public PublishController(BoardApplication gui, Board board) {
		this.board = (board);
		this.gui = (gui);
	}
	
	/**
	 *React to publish event. 
	 *Publish poem to wall and release words in the poem to unprotected area.
	 */
	public void publish(Poem p) {
		PoemDAO pd = new PoemDAO();
		ArrayList<Poem> poems = pd.findPublishedPoems(PoemDAO.FILE_NAME);
		
		if(poems == null || poems.isEmpty()){
			poems = new ArrayList<Poem>();
		}
		
		p.setPublishedOn(new Date());
		
		poems.add(p);
		
		pd.savePublishedPoems(poems, gui.getRunMode(), PoemDAO.FILE_NAME);
		pd.savePublishedPoemsHTML(poems, PoemDAO.HTML_FILE_NAME);
		
		board.release(p);
		gui.canvas.repaint();
		
		BoardMemento bm = new BoardMemento(board);
		BoardMementoDAO dao = new BoardMementoDAO();
		dao.saveBoardMemento(bm, gui.getRunMode(), BoardMementoDAO.FILE_NAME);
	}
}